package pl.edu.uj.ii.battleships.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import pl.edu.ii.uj.battleships.server.ServerHandler;
import pl.edu.uj.ii.battleships.R;
import pl.edu.uj.ii.battleships.activities.MyBoardActivity.InsertStatus;
import pl.edu.uj.ii.battleships.adapters.GridAdapter;
import pl.edu.uj.ii.battleships.interfaces.Handler;
import pl.edu.uj.ii.battleships.models.BoardItem;
import pl.edu.uj.ii.battleships.utils.ConfigPropsManager;
import pl.edu.uj.ii.battleships.utils.GameDataManager;
import pl.edu.uj.ii.battleships.utils.Logger;

public class OpponentBoardActivity extends CustomActivity implements Handler {
	
	GridView gridView;
	GridAdapter adapter;
	InsertStatus currentStatus;
	TextView textview_info;
	TextView textview_count;
	TextView textview_title;
	Button button_change;
	Button button_start;
	ProgressDialog progressDialog;
	ServerHandler serverHandler;
	ConfigPropsManager propsManager;
	CheckBox placeDown;
	
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private GestureDetector gestureDetector;
    
    class MyGestureDetector extends SimpleOnGestureListener {
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        	Logger.debug("Something is going on. Gesture detected");
	    Intent intent = new Intent(OpponentBoardActivity.this.getBaseContext(), MyBoardActivity.class);
 
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
 
	    	    // right to left swipe
            if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	    		startActivity(intent);
	    		OpponentBoardActivity.this.overridePendingTransition(
					R.anim.slide_in_left, 
					R.anim.slide_out_right
	    		);
            }
 
            return false;
        }
 
        // It is necessary to return true from onDown for the onFling event to register
        @Override
        public boolean onDown(MotionEvent e) {
	        	return true;
        }
    }
    
	final android.os.Handler customHandler = new android.os.Handler(){
		public void handleMessage(Message msg){
			String s = (String)msg.obj;
			Logger.debug("Handler received msg: " + s);
		}
	};
	
	public android.os.Handler getHandler() {
		return customHandler;
	}
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.board_layout);
        
        propsManager = new ConfigPropsManager(this);
        
        serverHandler = GameDataManager.getServerHandler();
        if(serverHandler == null)
        	serverHandler = new ServerHandler(propsManager, this);      
        
        serverHandler.setHandler(this);
        
        button_change = (Button)findViewById(R.id.button_change);
        button_change.setOnClickListener(onChangeButtonClickListener);
        button_change.setText("Your board");
        
        button_start = (Button)findViewById(R.id.button_start);
        button_start.setOnClickListener(onChangeButtonClickListener);
        button_start.setVisibility(View.GONE);
        
        
        gridView = (GridView)findViewById(R.id.gridview);
        gridView.setNumColumns(GameDataManager.getBoardWidth());
        
        adapter = new GridAdapter(this);
        gridView.setAdapter(adapter);
        
        gridView.setOnItemClickListener(itemClickListener);
        
        textview_info = (TextView)findViewById(R.id.textView_info);
        textview_count = (TextView)findViewById(R.id.textView_count);
        textview_title = (TextView)findViewById(R.id.textview_title);
        
        textview_info.setText("");
        textview_count.setVisibility(View.GONE);
        textview_title.setText("Opponent board");
        
        placeDown = (CheckBox)findViewById(R.id.insert_direction);
        placeDown.setVisibility(View.GONE);
        
		gestureDetector = new GestureDetector(new MyGestureDetector());
		
        View mainview = (View) findViewById(R.id.mainView);
        
        // Set the touch listener for the main view to be our custom gesture listener
        mainview.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
        
	}
	
	private OnItemClickListener itemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			BoardItem bi = adapter.getItem(position);
			Logger.debug("Item clicked. Position: " + position + " , Id: " + id + " Status: " + bi.getStatus());
			//send the position to opponent and wait for response if hit or miss
		}
	};
	
	private OnClickListener onChangeButtonClickListener = new OnClickListener() {

		public void onClick(View v) {
			if(v.equals(button_change)){
				Logger.debug("Your board button clicked.");
				Intent intent = new Intent(v.getContext(), MyBoardActivity.class);
				startActivityForResult(intent, 0);
			}
		}
		
	};
}
